﻿using DidaCode.Workflow.Logs;
using DidaCode.Workflow.NodeAttribute;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace DidaCode.Workflow.Help
{
    public static class ProcessDataStorage
    {
        // 存储容器，Key 为特性名称，Value 为属性值
        private static readonly AsyncLocal<ConcurrentDictionary<string, object>> _asyncLocalStorage = new AsyncLocal<ConcurrentDictionary<string, object>>();
        private static ConcurrentDictionary<string, object> LocalStorage => _asyncLocalStorage.Value ??= new ConcurrentDictionary<string, object>();

        public static void Init()
        {
            _asyncLocalStorage.Value = new ConcurrentDictionary<string, object>();
            _asyncLocalStorage.Value["Init"] = "Init";
            Console.WriteLine($"[Thread: {Thread.CurrentThread.ManagedThreadId}] Init");
        }

        /// <summary>
        /// 存储带有指定 NodeType 特性的属性值
        /// </summary>
        /// <param name="source">源对象</param>
        public static void StoreData(object source)
        {
            var sourceType = source.GetType();
            var properties = PropertyHelp.GetCachedProperties(sourceType);
            foreach (var property in properties)
            {
                var value = property.Getter(source);
                if (value != null)
                {
                    LocalStorage[property.AttributeName] = value;
                }
            }
        }

        /// <summary>
        /// 从存储中获取指定特性名称的值
        /// </summary>
        /// <param name="nodeTypeName">特性名称</param>
        /// <returns>属性值</returns>
        public static object? GetData(string key)
        {
            if (key == null)
                return null;
            LocalStorage.TryGetValue(key, out var value);
            return value;
        }
        private static readonly object _lock = new();

        /// <summary>
        /// 清除当前异步上下文的存储数据
        /// </summary>
        public static void Clear()
        {
            lock (_lock)
            {
                LocalStorage.Clear();
            }
        }

        /// <summary>
        /// 获取当前上下文的存储字典（用于批量操作）
        /// </summary>
        public static ConcurrentDictionary<string, object> GetCurrentStorage()
        {
            return LocalStorage;
        }
    }

    // 流程执行器
    public static class ProcessExecutor
    {
        /// <summary>
        /// 自动从存储中赋值到目标对象
        /// </summary>
        /// <typeparam name="TTarget">目标对象类型</typeparam>
        /// <param name="target">目标对象</param>
        public static void AutoAssignFromStorage<TTarget>(TTarget target)
        {
            if (target == null) throw new ArgumentNullException(nameof(target));
            var targetType = target.GetType();
            var properties = PropertyHelp.GetCachedProperties(targetType);
            var localStorage = ProcessDataStorage.GetCurrentStorage();
            foreach (var property in properties)
            {
                if (localStorage.TryGetValue(property.AttributeName, out var value) &&
                    value != null && property.Setter != null)
                {
                    property.Setter(target, value);
                }
            }
        }
    }
}
